package tile

import "math"

const (
	earthRadius = 6378137.0
	originShift = 2 * math.Pi * earthRadius / 2.0
)

// 经纬度转墨卡托投影坐标
func Mercator(lat, lon float64) (x, y float64) {
	x = lon * originShift / 180.0
	y = math.Log(math.Tan((90+lat)*math.Pi/360)) / (math.Pi / 180)
	y = y * originShift / 180.0
	return
}

// 计算瓦片坐标
func TileCoordinate(x, y float64, zoom int) (xtile, ytile int) {
	tiles := math.Pow(2, float64(zoom))
	xtile = int(math.Floor((x + originShift) / (2 * originShift) * tiles))
	ytile = int(math.Floor((originShift - y) / (2 * originShift) * tiles))
	return
}

// 像素坐标转瓦片内偏移量
func PixelOffset(x, y float64, tileSize int) (px, py int) {
	xScaled := x * float64(tileSize)
	yScaled := y * float64(tileSize)
	return int(xScaled), int(yScaled)
}
